﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Caltech.Models;
using Caltech.Service.Common;
using CaltechSoft.Service.EntityFW.Entity;
using CaltechSoft.Service.EntityFW.Repository;
using CaltechSoft.Service.Repositories;
using System.Linq.Expressions;
using LinqKit;
using System.Threading.Tasks;
using AutoMapper;
using System.Security.Claims;
using Microsoft.AspNet.Identity;
using Caltech.Extensions;
using Caltech.Results;

namespace Caltech.Controllers
{
    [HasAccess(Areas.AEView)]
    public class AEController : BaseApiController<AE, AEModel, AEModel>
    {
        public RoleManager<Role> RoleManager { get; private set; }

        public AEController(IRepository<AE> repository, RoleManager<Role> roleManager)
            : base(repository)
        {
            RoleManager = roleManager;
        }

        public override IHttpActionResult Get()
        {
            var queryItems = Request.RequestUri.ParseQueryString();
            string customerName = queryItems["customerName"];
            string poNo = queryItems["poNo"];
            int customerId;

            Expression<Func<AE, bool>> filter = null;

            if (int.TryParse(queryItems["customerId"], out customerId))
            {
                filter = quote => quote.Company.Id == customerId;
            }
            else if (!string.IsNullOrEmpty(customerName))
            {
                filter = quote => quote.Company.Name.ToLower().Contains(customerName.ToLower());
            }

            if (!string.IsNullOrEmpty(poNo))
            {
                if (filter == null)
                {
                    filter = ae => ae.PONo.ToLower().Contains(poNo.ToLower());
                }
                else
                {
                    filter.And(ae => ae.PONo.ToLower().Contains(poNo.ToLower()));
                }
            }

            int? page = TryParseInt(queryItems["page"]);
            int? count = TryParseInt(queryItems["count"]);

            int total;
            var entities = Repository.DbSet().AsExpandable().OrderByDescending(x => x.Id).AsQueryable();

            if (filter != null)
            {
                entities = entities.Where(filter);
                total = entities.Count();
            }
            else
            {
                total = entities.Count();
            }

            if (count.HasValue && page.HasValue)
            {
                entities = entities.Skip(count.Value * (page.Value - 1)).Take(count.Value);
            }
            else
            {
                entities = entities.Take(10);
            }

            var model = Mapper.Map<IEnumerable<AEModel>>(entities);
            model.ForEach(x =>
            {
                x.AENoView = String.Format("{0}-{1}", x.CreatedDate.Value.ToString("yy"), String.Format("{0:0000}", x.Id));
            });
            return Request.CreateSearchResult<AEModel>(model, total);
        }

        public override async Task<IHttpActionResult> GetBy(int id)
        {
            var entity = await Repository.GetBy(id);
            var model = Mapper.Map<AEModel>(entity);

            if (model == null)
            {
                return NotFound();
            }

            if(RoleManager.Roles.Count() > 0)
            { 
                var role =  RoleManager.Roles.Where(x=> x.Id ==  model.User.RoleId).FirstOrDefault();
                if(role != null)
                {
                    model.User.RoleName = role.Name;
                }
            }
            model.AENoView = String.Format("{0}-{1}", model.CreatedDate.Value.ToString("yy"), String.Format("{0:0000}", model.Id));
            return Ok(model);
        }

        [HasAccess(Areas.AECreate)]
        public override async Task<IHttpActionResult> Post(AEModel model)
        {
            return await base.Post(model);
        }

        [HasAccess(Areas.AEEdit)]
        public override async Task<IHttpActionResult> Put(AEModel model)
        {
            return await base.Put(model);
        }

        [HasAccess(Areas.AEDelete)]
        public override async Task<IHttpActionResult> Delete(int id)
        {
            return await base.Delete(id);
        }
    }
}